package com.example.compose

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.forEachGesture
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Canvas
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.tooling.preview.Preview

@Preview
@Composable
fun MultiTouchCanvas() {
    // 记录触摸点的坐标
    val touchPoints = remember { mutableStateOf(emptyList<Offset>()) }
    val scope = rememberCoroutineScope()

    Canvas(modifier = Modifier
        .fillMaxSize()
        .pointerInput(Unit) {
            // 处理多点触控事件
            forEachGesture {
//                scope.launch {
                // 对每个触控事件进行处理
                awaitPointerEventScope {
                    while (true) {
                        val event = awaitPointerEvent()
                        // 获取所有触控点的坐标
                        val points = event.changes.map { it.position }
                        // 更新触控点的列表
                        touchPoints.value = points
                    }
                }
//                }
            }
        }
    ) {

        // 在画布上绘制触控点
        drawIntoCanvas { canvas ->
            drawTouchPoints(canvas, touchPoints.value)
        }
    }
}

private fun drawTouchPoints(canvas: Canvas, points: List<Offset>) {
    canvas.apply {
        for (point in points) {
            drawCircle(paint = Paint(), radius = 30f, center = point)
        }
    }
}
